// pages/student/kechenbiao/kechenbiao.js
const app = getApp();

Page({
  // 在data中添加或修改以下属性
  data: {
    // 学期信息将从后端获取
    semesters: [],
    semesterValues: [],
    currentSemesterIndex: 0,
    currentWeek: 1,
    // 修改为动态获取周数，初始设置一个合理的默认值
    weeks: Array.from({length: 20}, (_, i) => `第${i + 1}周`),
    maxWeeks: 20, // 添加最大周数变量
    currentWeekIndex: 0,
    weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    timeSlots: ['1-2节', '3-4节', '5-6节', '7-8节', '9-10节'],
    userRole: 'student',
    
    // 课程表数据
    timetableData: [],
    
    // 处理后的课程表显示数据
    displayTimetable: [],
    
    // 加载状态
    isLoading: true
  },
  
  onLoad: function() {
    console.log('课程表页面加载');
    // 初始化空的课程表
    this.initEmptyTimetable();
    
    // 获取用户角色
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.role) {
      this.setData({
        userRole: userInfo.role
      });
    }
    
    // 计算当前学期和周次
    this.calculateCurrentSemesterAndWeek();
    
    // 获取学期列表
    this.fetchSemesters();
  },
  
  onShow: function() {
    console.log('课程表页面显示');
  },
  
  onPullDownRefresh: function() {
    this.fetchTimetableData();
  },
  
  // 计算当前学期和周次
  calculateCurrentSemesterAndWeek: function() {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1; // 月份从0开始，所以+1
    
    // 确定当前学期
    let currentSemester;
    if (currentMonth >= 2 && currentMonth <= 7) {
      // 2-7月为第二学期
      currentSemester = `${currentYear-1}-${currentYear}-2`;
    } else {
      // 8-1月为第一学期
      currentSemester = `${currentYear}-${currentYear+1}-1`;
    }
    
    // 计算当前周次
    let currentWeek = 1;
    let semesterStart;
    
    if (currentMonth >= 2 && currentMonth <= 7) {
      // 第二学期从2月开始
      semesterStart = new Date(currentYear, 1, 1); // 2月1日
    } else if (currentMonth >= 8) {
      // 第一学期从9月开始
      semesterStart = new Date(currentYear, 8, 1); // 9月1日
    } else {
      // 1月属于上一年的第一学期
      semesterStart = new Date(currentYear - 1, 8, 1); // 上一年9月1日
    }
    
    const diffTime = Math.abs(now - semesterStart);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    currentWeek = Math.ceil(diffDays / 7);
    
    // 确保周次在合理范围内
    currentWeek = Math.min(Math.max(currentWeek, 1), 20);
    
    console.log('计算得到的当前学期和周次:', { currentSemester, currentWeek });
    
    this.setData({
      currentSemester: currentSemester,
      currentWeek: currentWeek,
      currentWeekIndex: currentWeek - 1 // 索引从0开始
    });
  },
  
  // 初始化空的课程表
  initEmptyTimetable: function() {
    const emptyTable = Array(7).fill().map(() => Array(5).fill(null));
    this.setData({
      displayTimetable: emptyTable
    });
  },
  
  // 获取学期列表
  fetchSemesters: function() {
    console.log('获取学期列表');
    wx.showLoading({
      title: '加载中...',
    });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/courses/semesters`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        console.log('获取学期列表成功:', res.data);
        if (res.statusCode === 200) {
          const semesters = res.data || [];
          
          if (semesters.length > 0) {
            // 转换为前端需要的格式，添加空值检查
            const semesterNames = semesters.map(item => {
              // 检查item是否为字符串
              const semesterId = typeof item === 'object' ? (item.id || '') : item || '';
              
              // 添加空值检查
              if (semesterId && typeof semesterId === 'string') {
                const parts = semesterId.split('-');
                if (parts.length === 3) {
                  const startYear = parts[0];
                  const endYear = parts[1];
                  const term = parts[2] === '1' ? '第一学期' : '第二学期';
                  return `${startYear}-${endYear}学年${term}`;
                }
              }
              // 如果无法解析，返回原始值或默认值
              return typeof item === 'object' ? (item.name || '未知学期') : (item || '未知学期');
            });
            
            // 同样为semesterValues添加空值检查
            const semesterValues = semesters.map(item => {
              return typeof item === 'object' ? (item.id || '') : (item || '');
            });
            
            // 查找当前学期在列表中的索引
            let currentSemesterIndex = 0;
            const currentSemesterValue = this.data.currentSemester;
            
            semesterValues.forEach((value, index) => {
              if (value === currentSemesterValue) {
                currentSemesterIndex = index;
              }
            });
            
            this.setData({
              semesters: semesterNames,
              semesterValues: semesterValues,
              currentSemesterIndex: currentSemesterIndex
            });
            
            console.log('设置学期数据:', {
              names: semesterNames,
              values: semesterValues,
              currentIndex: currentSemesterIndex
            });
          } else {
            // 如果没有获取到学期数据，使用默认值
            const currentYear = new Date().getFullYear();
            this.setData({
              semesters: [`${currentYear}-${currentYear+1}学年第一学期`, `${currentYear-1}-${currentYear}学年第二学期`],
              semesterValues: [`${currentYear}-${currentYear+1}-1`, `${currentYear-1}-${currentYear}-2`],
              currentSemesterIndex: 0
            });
            console.log('使用默认学期数据');
          }
        } else {
          console.log('获取学期列表失败，使用默认值');
          // 使用默认值
          const currentYear = new Date().getFullYear();
          this.setData({
            semesters: [`${currentYear}-${currentYear+1}学年第一学期`, `${currentYear-1}-${currentYear}学年第二学期`],
            semesterValues: [`${currentYear}-${currentYear+1}-1`, `${currentYear-1}-${currentYear}-2`],
            currentSemesterIndex: 0
          });
        }
        
        // 获取完学期后，获取课程表数据
        this.fetchTimetableData();
      },
      fail: (err) => {
        console.log('获取学期列表请求失败:', err);
        // 请求失败时使用默认值
        const currentYear = new Date().getFullYear();
        this.setData({
          semesters: [`${currentYear}-${currentYear+1}学年第一学期`, `${currentYear-1}-${currentYear}学年第二学期`],
          semesterValues: [`${currentYear}-${currentYear+1}-1`, `${currentYear-1}-${currentYear}-2`],
          currentSemesterIndex: 0
        });
        
        // 获取课程表数据
        this.fetchTimetableData();
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  
  // 获取课程表数据
  // 修改fetchTimetableData函数，确保正确处理返回的数据
  fetchTimetableData: function() {
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    // 获取当前选择的学期和周次
    const semester = this.data.semesterValues[this.data.currentSemesterIndex];
    const week = this.data.currentWeek;
    
    console.log('获取课表数据，参数:', { semester, week });
    
    this.setData({ isLoading: true });
    
    wx.request({
      url: `${serverUrl}/api/courses/timetable/student`,
      method: 'GET',
      data: {
        week: week,
        semester: semester
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        console.log('课表API返回数据:', res.data);
        
        if (res.statusCode === 200) {
          // 检查返回的数据是否为数组
          if (Array.isArray(res.data)) {
            // 处理课程数据
            this.processTimetableData(res.data);
          } else {
            console.error('返回的数据不是数组:', res.data);
            // 初始化空的课程表
            this.initEmptyTimetable();
            wx.showToast({
              title: '课表数据格式错误',
              icon: 'none'
            });
          }
        } else {
          console.log('获取课表数据失败:', res);
          // 初始化空的课程表
          this.initEmptyTimetable();
          wx.showToast({
            title: '获取课表失败',
            icon: 'none'
          });
        }
        this.setData({ isLoading: false });
      },
      fail: (err) => {
        console.log('获取课表数据失败:', err);
        // 初始化空的课程表
        this.initEmptyTimetable();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ isLoading: false });
      }
    });
  },
  
  // 修改处理课程表数据的函数，添加更好的错误处理
  processTimetableData: function(courses) {
    console.log('处理课程表数据:', courses);
    
    // 确保courses是数组
    if (!Array.isArray(courses)) {
      console.error('课程数据不是数组');
      this.initEmptyTimetable();
      return;
    }
    
    // 创建一个空的课程表显示数组
    const displayTimetable = Array(7).fill().map(() => Array(5).fill(null));
    
    // 遍历课程数据，填充到显示数组中
    courses.forEach(course => {
      try {
        // 确保day和period在有效范围内
        const dayIndex = parseInt(course.day) - 1; // 转为0-6的索引
        
        // 根据period确定在哪个时间段显示
        let periodIndex;
        const period = parseInt(course.period);
        
        if (period <= 2) periodIndex = 0;      // 1-2节
        else if (period <= 4) periodIndex = 1; // 3-4节
        else if (period <= 6) periodIndex = 2; // 5-6节
        else if (period <= 8) periodIndex = 3; // 7-8节
        else periodIndex = 4;                  // 9-10节
        
        console.log(`课程 ${course.courseName} 的位置: 第${dayIndex+1}天, 第${periodIndex+1}时段`);
        
        if (dayIndex >= 0 && dayIndex < 7 && periodIndex >= 0 && periodIndex < 5) {
          displayTimetable[dayIndex][periodIndex] = {
            id: course.id,
            name: course.courseName || '未知课程',
            teacher: course.teacherName || '未知教师',
            location: course.roomName || '未知地点',
            day: course.day,
            period: course.period,
            startWeek: course.startWeek,
            endWeek: course.endWeek
          };
        }
      } catch (error) {
        console.error('处理课程数据时出错:', error, course);
      }
    });
    
    this.setData({
      displayTimetable: displayTimetable
    });
    
    console.log('处理后的课程表显示数据:', displayTimetable);
  },
  
  // 判断指定位置是否有课程
  hasCourse: function(dayIndex, timeIndex) {
    return this.data.displayTimetable && 
           this.data.displayTimetable[dayIndex] && 
           this.data.displayTimetable[dayIndex][timeIndex];
  },
  
  // 获取指定位置的课程
  getCourse: function(dayIndex, timeIndex) {
    if (this.hasCourse(dayIndex, timeIndex)) {
      return this.data.displayTimetable[dayIndex][timeIndex];
    }
    return null;
  },
  
  // 获取课程的样式类
  getCourseClass: function(dayIndex, timeIndex) {
    if (this.hasCourse(dayIndex, timeIndex)) {
      const courseId = this.data.displayTimetable[dayIndex][timeIndex].id;
      return `has-course course-${(courseId % 5) + 1}`;
    }
    return '';
  },
  
  // 切换学期
  changeSemester: function(e) {
    const semesterIndex = e.detail.value;
    console.log('切换学期:', this.data.semesters[semesterIndex]);
    this.setData({
      currentSemesterIndex: semesterIndex
    });
    
    // 重新获取课程表数据
    this.fetchTimetableData();
  },
  
  // 切换周次
  changeWeek: function(e) {
    const index = parseInt(e.detail.value);
    const week = index + 1;
    
    // 确保周次不超过最大值
    if (week <= this.data.maxWeeks) {
      this.setData({
        currentWeekIndex: index,
        currentWeek: week
      }, () => {
        // 重新加载课程表数据
        this.fetchTimetableData();
      });
    }
  },
  
  // 查看课程详情
  viewCourseDetail: function(e) {
    const { day, time } = e.currentTarget.dataset;
    console.log('点击课程:', day, time);
    
    if (!this.data.displayTimetable || !this.data.displayTimetable[day] || !this.data.displayTimetable[day][time]) {
      console.log('该位置没有课程');
      return;
    }
    
    const course = this.data.displayTimetable[day][time];
    console.log('查看课程详情:', course);
    
    // 如果有详情页，跳转到详情页
    if (course.id) {
      // 将课程数据编码为URL参数
      const courseData = encodeURIComponent(JSON.stringify({
        id: course.id,
        name: course.name,
        teacher: course.teacher,
        location: course.location,
        day: parseInt(day) + 1, // 转换为1-7的格式
        period: parseInt(time),
        startWeek: course.startWeek,
        endWeek: course.endWeek
      }));
      
      wx.navigateTo({
        url: `/pages/student/kechenbiao/detail/detail?id=${course.id}&data=${courseData}`
      });
    } else {
      // 否则直接显示简单的课程信息
      wx.showModal({
        title: course.name || '课程信息',
        content: `教师: ${course.teacher || '未知'}\n地点: ${course.location || '未知'}\n周次: 第${course.startWeek || 1}-${course.endWeek || 20}周`,
        showCancel: false
      });
    }
  }
});